<script>
/* eslint-disable no-undef */
import MyBase from '@/common/formComponent/MyBase';
import UniIcon from 'uview-ui/components/u-icon/u-icon';
import UniImage from 'uview-ui/components/u-image/u-image.vue';
import WCompress from '@/components/w-compress/w-compress.vue';
import MyFileRow from '@/common/formComponent/components/MyFileRow';
import { api as viewerApi } from 'v-viewer';

import {
  chooseImgs,
  conversionBase64,
  dataURLtoFile,
  chooseFileUni
} from '@/utils/files';

export default {
  name: 'MyPicChoose',

  components: {
    MyBase
  },

  model: {
    prop: 'value',
    event: 'update:value'
  },

  props: {
    value: {
      type: [String, Array],
      default: ''
    },

    title: {
      type: String,
      default: ''
    },

    isShowIconArrow: {
      type: Boolean,
      default: true
    },

    mode: {
      type: String,
      default: 'pic' // file | pic
    },

    placeholder: {
      type: String,
      default: '请输入'
    },

    loading: {
      type: Boolean,
      default: false
    },

    disabled: {
      type: Boolean,
      default: false
    },

    icon: {
      type: String,
      default: '' // moments
    }
  },

  data() {
    return {
      /*
          mode === pic
          {
            img,
            file
          }

          mode === file
          {
            file
          }
      */
      fileList: []
    };
  },

  computed: {
    icon1() {
      return this.mode === 'pic' ? 'photo' : require('@/static/img/task/tasklink.png');
    }
  },

  methods: {
    chooseFile() {
      switch (this.mode) {
        case 'pic':
          this.chooseImg();
          break;

        case 'file':
          this.chooseFileReal();
          break;

        default:
          break;
      }
    },

    chooseFileReal() {
      const { value: fileList1 } = this;
      const fileList = fileList1 || [];
      chooseFileUni().then(files => {
        const tookedFiles = files.map(file => ({ file }));
        this.setData([...fileList, ...tookedFiles]);
      });
    },

    chooseImg() {
      const wCompress = this.$refs.wCompress;
      const { setData, value: fileList1 } = this;
      const fileList = fileList1 || [];

      chooseImgs().then(({ files }) => {
        uni.showLoading({
          title: '压缩中'
        });

        const wait = files.map((file) => {
          return conversionBase64(new Blob([file], { type: file.type }));
        });

        Promise.allSettled(wait).then((values) => {
          const imgs64 = values.map((o) => o.value);

          wCompress.start(imgs64).then((res) => {
            const filesContainer = [];
            setTimeout(() => {
              uni.hideLoading();
            }, 500);
            res.map((b64, i) => {
              const file = dataURLtoFile(b64, files[i].name);
              filesContainer.push({
                img: b64,
                file
              });
            });

            setData([...fileList, ...filesContainer]);
          });
        });
      });
    },

    imgView(pic, index) {
      viewerApi({
        options: {
          toolbar: true,
          initialViewIndex: index
        },
        images: this.value.map(o => o.img)
      });
    },

    setData(data) {
      if (!this.disabled) {
        this.$emit('update:value', data);
      }
    }
  },

  render(h) {
    const compressInstance = h(WCompress, {
      ref: 'wCompress',
      props: {
        pixels: 500000
      }
    });

    const baseSlots = {
      header: () => {
        return (
          <view class='MyPicChoose_header'>
            <text>{this.title}</text>
            {
              h(UniIcon, {
                class: 'title_icon',
                props: {
                  size: '68',
                  color: '#1492FF',
                  name: this.icon1
                },

                on: {
                  click: () => {
                    if (!this.disabled) {
                      this.chooseFile();
                    }
                  }
                }
              })
            }
          </view>
        );
      },

      content: () => {
        const empty = (
          <view class='bodyHeight MyPicChoose_content_file MyPicChoose_content_empty'>
            { this.loading ? '' : this.placeholder}
          </view>
        );

        const dataList = this.value || [];

        const contentBody = this.mode === 'pic'
          // 图片
          ? h('view',
            [
              (
                <view class='MyPicChoose_content_pic '>
                  {
                    dataList.map((pic, i) => h(
                      UniImage,
                      {
                        class: 'animate__animated animate__slideInUp',
                        props: {
                          src: pic.img,
                          height: '78px',
                          mode: 'center',
                          borderRadius: '4px'
                        },

                        on: {
                          click: () => this.imgView(pic, i)
                        }
                      }
                    ))
                  }
                </view>
              ),
              compressInstance
            ])

        // 文件
          : (
            <view class='MyPicChoose_content_file'>
              {
                h(MyFileRow, {
                  props: {
                    fileList: dataList,
                    loading: this.loading
                  }
                })
              }
            </view>
          );
          // value 空
          // : compressInstance;

        return h(
          'view',
          [
            contentBody,
            this.value ? '' : empty
          ]
        );
      }
    };

    return (
      <view>
        <My-Base
          isShowIconArrow={false}
          scopedSlots={baseSlots}
          icon=''
        />
      </view>
    );
  }
};
</script>

<style lang="scss" scoped>
.MyPicChoose_header {
  display: flex;
  justify-content: space-between;
  width: 100%;

  .title_icon {
    position: relative;
    top: -5px;
    right: -10px;
  }
}

.bodyHeight {
  min-height: 58px;
}

.MyPicChoose_content_pic {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.MyPicChoose_content_file {
  display: block;
}

.MyPicChoose_content_empty {
  flex-direction: row;
  align-items: flex-end;
}

</style>
